/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.metagurukul.metaspace.actions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.metagurukul.metaspace.controller.ChangePictureForm;
import com.metagurukul.metaspace.service.UserService;

/**
 * Change Picture page is to change your current profile picture for success
 * redirects to view Profile For failure it is send to again to same page.
 * 
 * @author himanshu
 * 
 * @see Action
 */
public class ChangePictureAction extends org.apache.struts.action.Action {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.
	 * ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException, SQLException{
		ChangePictureForm uploadForm = (ChangePictureForm) form;
		FileOutputStream outputStream = null;
		FormFile formFile = null;
		try {
			formFile = uploadForm.getSelectFile();
			String fileName = formFile.getFileName();
			HttpSession session = request.getSession(true);
			int userId = (Integer) session.getAttribute("id");
			String path = getServlet().getServletContext().getRealPath(
					"resources/images/users")
					+ "\\" + formFile.getFileName();

			outputStream = new FileOutputStream(new File(path));
			outputStream.write(formFile.getFileData());
			UserService.updateProfilePic(fileName, userId);
			response.sendRedirect("/jsp/changedPicture.jsp");
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
		return mapping.findForward("failure");
	}
}
